package com.xincheng.library.retrofit;

import com.xincheng.library.common.BaseConfig;
import com.xincheng.library.xlog.XLog;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by pc on 2016/8/23.
 */
public class RetrofitManager {

    private static RetrofitManager instance;

    private OkHttpClient okHttpClient;

    private Disposable disposable;

    protected RetrofitManager() {
        initHttpClient();
    }

    public static RetrofitManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }

    private void initHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置 Debug Log 模式
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                XLog.d(message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logging);
        builder.connectTimeout(BaseConfig.CONNECT_TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(BaseConfig.READ_TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(BaseConfig.WRITE_TIMEOUT, TimeUnit.SECONDS);
        okHttpClient = builder.build();
    }

    /**
     * 获取retrofit对象
     */
    public Retrofit getRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    //解除被观察者的绑定
    public void unSubscription() {
        if (disposable != null) {
            disposable.dispose();
        }
    }

}
